package com.gmrz.uap.common;

import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.model.Role;
import com.gmrz.uap.model.User;
import com.gmrz.uap.model.UserRole;
import com.jfinal.core.Controller;
import com.jfinal.i18n.Res;
import com.jfinal.render.JsonRender;
import org.apache.commons.collections4.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller公共类，存放一些公用的变量和方法
 */
public class ControllerSupport extends Controller {

    protected Map<String, Object> result = new HashMap<String, Object>();
    protected Map<String, Object> condition = new HashMap<String, Object>();
    protected String message = null;
    protected boolean flag = false;
    protected int flagInt = 0;
    protected StringBuffer sql = new StringBuffer();


    protected Res getRes() {
        return new Res("i18n", getCookie("_locale", SystemConst.SYSTEM_DEFAULT_LOCALE));
    }

    /**
     * 如果浏览器为IE的话则响应的ContentType为text/html,来解决IE中AJAX下载问题，同时解决MAC系统中safari插件在返回报文中增加内容的问题
     *
     * @return JosnRender
     */
    protected JsonRender responseJsonRender(Object object) {
        String userAgent = getRequest().getHeader("User-Agent").toLowerCase();
        JsonRender jsonRender;
        // 根据User-Agent判断浏览器是否为IE浏览器，rv:11 是判断是否为IE11版本的
        if (userAgent.contains("msie") || userAgent.contains("rv:11")) {
            jsonRender = new JsonRender(object).forIE();
        } else {
            jsonRender = new JsonRender(object);
        }

        return jsonRender;
    }

    public static JsonRender responseJsonRender(Object object, HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent").toLowerCase();
        JsonRender jsonRender;
        if (userAgent.contains("msie") || userAgent.contains("rv:11")) {
            jsonRender = new JsonRender(object).forIE();
        } else {
            jsonRender = new JsonRender(object);
        }

        return jsonRender;
    }


    public boolean isTherePermissions(){
        List<String> roleList = new ArrayList<>();
        // 超级管理员
        roleList.add(Role.dao.getRoleNameById(SystemConst.SUPER_ROLE_ID));
        // 省级管理员
        roleList.add(Role.dao.getRoleNameById(SystemConst.PROVINCE_ROLE_ID));

        // 从缓存中取出"当前"用户信息
        User cacheUser = UAPSSOHelper.getUserByUapSessionId(getRequest());
        List<String> roles = UserRole.dao.getRoleName(cacheUser.getUserId());
        if (roles != null){
            // 求两个集合的交集
            List<String> intersection = (List<String>) CollectionUtils.intersection(roleList, roles);
            if (intersection !=null && intersection.size() >0){
                return true;
            }
        }
        return false;
    }

}
